/**
 * Created by pan on 2018年02月07日14:25:52.
 */
const express = require('express');
const router = express.Router();
const superagent = require('superagent');

const fetchData = id => {
    return new Promise(resolve => {
        resolve(
            superagent.get(
                `https://api04ssfv.zhuishushenqi.com/book/${id}?t=1548899876801&useNewCat=true`
            )
        );
    });
};

const getRecommend = id => {
    return new Promise(resolve => {
        resolve(
            superagent.get(
                `https://api04ssfv.zhuishushenqi.com/book/${id}/recommend?packageName=com.ifmoc.ZhuiShuShenQi`
            )
        );
    });
};

const getAuthorOther = author => {
    console.log(author, 'author');
    return new Promise(resolve => {
        resolve(
            superagent.get(
                `https://api04ssfv.zhuishushenqi.com/book/accurate-search?author=${encodeURIComponent(
                    author
                )}&packageName=com.ifmoc.ZhuiShuShenQi&bookId=5b7bdc65e68fe87241f6c6ad`
            )
        );
    });
};

const getSource = id => {
    return new Promise(resolve => {
        resolve(
            superagent.get(
                `https://api04ssfv.zhuishushenqi.com/btoc?view=summary&book=${id}`
            )
        );
    });
};

router.get('/', async function(req, res, next) {
    if (req.query.bookid) {
        const result = await fetchData(req.query.bookid);
        const { body } = result;
        const recommend = await getRecommend(req.query.bookid);
        const source = await getSource(req.query.bookid);
        const other = await getAuthorOther(body.author);

        body.cover = decodeURIComponent(body.cover).replace(/\/agent\//, '');
        recommend.body.books.map(
            v =>
                (v.cover = decodeURIComponent(v.cover).replace(/\/agent\//, ''))
        );
        other.body.books.map(
            v =>
                (v.cover = decodeURIComponent(v.cover).replace(/\/agent\//, ''))
        );
        res.json({
            result: 1,
            data: {
                detail: result.body,
                recommend: recommend.body.books,
                other: other.body.books,
                source: source.body,
            },
        });
    } else {
        res.json({
            result: 0,
            msg: '非法参数',
        });
    }
});

module.exports = router;
